/*
 * Copyright (c) 2025 GuoKaiHong (Shenzhen) Technology Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { FileUtils } from './FileUtils';
import { BusinessError } from '@ohos.base';
import log from './Log'
import { common, Context } from '@kit.AbilityKit';

const TAG = 'NameMapUtil';

/**
 * 外设名称映射工具类
 */
export class NameMapUtil {
  private static TAG = "ConfigUtils";

  static nameMap: any = null;

  /**
   * 初始化配置信息
   *
   * @param context 上下文
   */
  static initConfig(context: common.UIAbilityContext) {
    // 读取rawfile文件内容
    FileUtils.getRawFileContent(context, "PeripheralNameMap.json").then((value: Uint8Array) => {
      let mapContent = FileUtils.uint8Array2Str(value);
      log(NameMapUtil.TAG, `getRawFileContent length is ${value.length}`)
      // 转换json对象
      this.nameMap = JSON.parse(mapContent)
      log(NameMapUtil.TAG, `getRawFileContent value is ${JSON.stringify(this.nameMap)}`)
    }).catch((error: BusinessError) => {
      log(NameMapUtil.TAG, `getRawFileContent failed, error code is ${error.code}, message is ${error.message}`)
    })
  }

  /**
   * 根据vid、pid获取名称
   *
   * @param vid 设备vid
   * @param pid 设备pid
   *
   * @returns 唯一标识已标准化的设备种类与IDL对应关联
   */
  static toName(vid: number, pid: number): string {
    let name = ""
    if (this.nameMap != null) {
      let peripherals = this.nameMap.peripherals;
      log(TAG, `toName peripherals: ${JSON.stringify(peripherals)}`)
      for (let item of peripherals) {
        log(TAG, `toName item: ${JSON.stringify(item)}`)
        let vpID = vid.toString() + '&' + pid.toString();
        log(TAG, `toName vpID: ${vpID}, vid: ${vid.toString()}, pid: ${pid.toString()}, item.VPID: ${item.VPID}`);
        if (vpID == item.VPID) {
          name = item.name;
          break;
        }
      }
    }
    return name;
  }

  static getMaxInteger(arr: any[]): number {
    const integerNumbers = arr.map(Number).filter(Number.isInteger);
    return Math.max(...integerNumbers);
  }
}